<template>
  <div class="app-container">
    <el-row>
      <!--区域数据-->
      <el-col :xs="24" v-show="treeVisibale === true" class="tree_bg">
        <!-- <div>
          <el-input
            v-model="keyWordName"
            placeholder="输入关键字进行过滤"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div> -->
        <div class="head-container">
          <el-tree
            :data="areaOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            v-loading="treeloading"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }">
              <i v-if="data.treeType === 2" class="el-icon-school" style="color: #40a0ffd3;font-size: 12px;"></i>
              <span style="font-size: 13px;"> {{ node.label }}</span>
            </span>
          </el-tree>
        </div>
        <div class="tree_close" @click="changeTreeShow">
          <i class="el-icon-caret-left" style="color: white"></i>
        </div>
      </el-col>
      <el-col class="jiange"></el-col>
      <div class="tree_open" @click="changeTreeShow" v-show="treeVisibale === false">
        <i class="el-icon-caret-right" style="color: white"></i>
      </div>
      <el-col :xs="24" :class="treeVisibale ? 'table_small_bg' : 'table_big_bg'">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" :size="size" v-show="showSearch" :label-width="labelWidth">
              <div id="searchFilter" style="display: flex; flex-wrap: wrap">
                <!-- <el-form-item label="归属楼栋编号" prop="ldId">
                  <el-input
                    v-model="queryParams.ldId"
                    placeholder="请输入归属楼栋编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item> -->
                <!-- <el-form-item label="楼层" prop="ldLc">
                  <el-input
                    v-model="queryParams.ldLc"
                    placeholder="请输入楼层"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item> -->
                <el-form-item label="门牌号" prop="roomName">
                  <el-input
                    v-model="queryParams.roomName"
                    placeholder="请输入门牌号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="楼栋名称" prop="ldName">
                  <el-input
                    v-model="queryParams.ldName"
                    placeholder="请输入楼栋名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="用户编号" prop="UserID">
                  <el-input
                    v-model="queryParams.UserID"
                    placeholder="请输入用户编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="设备编号" prop="TerminalID">
                  <el-input
                    v-model="queryParams.TerminalID"
                    placeholder="请输入设备编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item style="width: 0px;"></el-form-item>
              </div>
            </el-form>
          </el-col>
          <el-col class="form_query">
            <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
            <el-button @click="resetQuery" size="mini">重置</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8 padding_top_bottom">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['basedata:room:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['basedata:room:remove']"
            >批量删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
            >导入</el-button>
          </el-col>
          <RightDropdown :columns="columns" :showSearch.sync="showSearch" @queryTable="getList" @export="handleExport" :hasPermiExport="['basedata:room:export']"></RightDropdown>
        </el-row>

        <el-table v-loading="roomloading" :data="roomList" @selection-change="handleSelectionChange" ref="roomtable" max-height="600">
          <el-table-column type="selection" width="55" align="center" />
          <!-- <el-table-column label="平台表单主键" align="center" prop="ID" width="120" v-if="columns[0].visible" :show-overflow-tooltip="true"/> -->
          <!-- <el-table-column label="租户编号" align="center" prop="tenantId" v-if="columns[1].visible" :show-overflow-tooltip="true"/> -->
          <el-table-column label="归属楼栋" align="center" prop="ldName" v-if="columns[0].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="楼层" align="center" prop="ldLc" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="门牌号" align="center" prop="roomName" v-if="columns[2].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="建筑面积" align="center" prop="BuiltUpArea" v-if="columns[3].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="入住人数" align="center" prop="UserNumber" v-if="columns[4].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="用户编号" align="center" prop="UserID" v-if="columns[5].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="用户名称" align="center" prop="userName" v-if="columns[6].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="设备编号" align="center" prop="TerminalID" v-if="columns[7].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basedata:room:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-connection"
                @click="handleBindUser(scope.row)"
                v-if="scope.row.UserID === null || scope.row.UserID === ''"
                style="color: #a0d911"
              >绑定用户</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-thumb"
                @click="handleTransferUser(scope.row)"
                v-if="scope.row.UserID != null && scope.row.UserID != ''"
                style="color: #faad14"
              >房间过户</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-coordinate"
                @click="handleBindTerminal(scope.row)"
                v-if="scope.row.TerminalID === null || scope.row.TerminalID === ''"
                style="color: #a0d911"
              >绑表</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-sort"
                @click="handleTransferTerminal(scope.row)"
                v-if="scope.row.TerminalID != null && scope.row.TerminalID != ''"
                style="color: #faad14"
              >换表</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basedata:room:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改房间对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth" :inline="true">
        <!-- <el-form-item label="租户ID" prop="tenantId">
          <el-input v-model="form.tenantId" placeholder="请输入租户ID" />
        </el-form-item> -->
        <!-- <el-form-item label="归属水司" prop="tenantId">
          <el-select v-model="form.tenantId" placeholder="请选择归属水司" style="width: 202px;" :disabled="true">
            <el-option
              v-for="dict in dict.type.belong_department"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value.toString()"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="区域名称" prop="areaCode">
          <!-- <el-select v-model="form.areaCode" placeholder="请输入区域名称" style="width: 202px;" clearable @change="changeAreaSelect">  -->
            <!-- <el-input
              v-model="AreaName"
              placeholder="输入关键字进行过滤"
              clearable
              size="small"
              style="width: 80%;margin-left: 10%;"
              /> -->
            <!-- <el-option class="option" :value="selectOptions.id" :label="selectOptions.label" :key="selectOptions.id">
              <el-tree
                :data="areatreeOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterTreeNode"
                ref="areatree"
                node-key="id"
                default-expand-all
                highlight-current
                @node-click="handleSelectTree"
                class="tree"
                v-loading="areatreeLoading"
              />
            </el-option> -->
          <!-- </el-select> -->
          <treeselect v-model="form.areaCode" :options="areatreeOptions" :normalizer="normalizer" :show-count="true" placeholder="请选择区域名称" style="width:202px;"/>
        </el-form-item>
        <el-form-item label="归属楼栋" prop="ldId" value-key="ldName">
          <el-select v-model="form.ldId" placeholder="请输入归属楼栋" style="width: 202px;" filterable clearable :disabled="form.areaCode === null && title === '添加房间'? true : false" @change="handleldselect">
            <el-option v-for="(item, index) in lglist" :value="item.ldId" :label="item.ldName" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼层" prop="ldLc">
          <el-input v-model="form.ldLc" placeholder="请输入楼层" />
        </el-form-item>
        <el-form-item label="门牌号" prop="roomName">
          <el-input v-model="form.roomName" placeholder="请输入门牌号" />
        </el-form-item>
        <el-form-item label="建筑面积" prop="BuiltUpArea">
          <el-input v-model="form.BuiltUpArea" placeholder="请输入建筑面积" />
        </el-form-item>
        <el-form-item label="入住人数" prop="UserNumber">
          <el-input v-model="form.UserNumber" placeholder="请输入入住人数" />
        </el-form-item>
<!--        <el-form-item label="用户编号" prop="UserID">-->
<!--          <el-input v-model="form.UserID" placeholder="请输入用户编号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="设备编号" prop="TerminalID">-->
<!--          <el-input v-model="form.TerminalID" placeholder="请输入设备编号" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 房间过户 绑定用户弹窗 -->
    <el-dialog :title="title" :visible.sync="openBindUser" width="calc(100w -200px)" append-to-body @close="onCancel">
      <!-- 搜索 -->
      <el-row>
        <el-form :model="userQueryParams" ref="queryUserForm" size="small" label-width="100px" :inline="true">
          <!-- <el-form-item label="用户归属水司" prop="tenantId">
            <el-input
              v-model="userQueryParams.tenantId"
              placeholder="请输入用户归属水司"
              clearable
              @keyup.enter.native="handleQuery"
              class="input_w"
            />
          </el-form-item> -->
          <el-form-item label="用户名称" prop="UserName">
            <el-input
              v-model="userQueryParams.UserName"
              placeholder="请输入用户名称"
              clearable
              @keyup.enter.native="handleQueryUser"
              class="input_w"
            />
          </el-form-item>
          <el-form-item label="用户编号" prop="UserID">
            <el-input
              v-model="userQueryParams.UserID"
              placeholder="请输入用户编号"
              clearable
              @keyup.enter.native="handleQueryUser"
              class="input_w"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQueryUser" size="mini">查询</el-button>
            <el-button @click="resetUserQuery" size="mini">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!-- 表格 -->
      <!-- @selection-change="handleSelectionUser" -->
      <el-row>
        <el-table v-loading="userloading" :data="usersList"  @row-click="singleUserElection" highlight-current-row max-height="500" ref="userTable">
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column align="center" width="55" label="选择">
            <template slot-scope="scope">
              <el-radio v-model="templateUserSelection" :label="scope.row.ID" class="radio"><span v-html="'\u00a0'"></span></el-radio>
            </template>
          </el-table-column>
          <!-- <el-table-column label="自增主键" align="center" prop="ID" :show-overflow-tooltip="true"/> -->
          <!-- <el-table-column label="用户归属水司" align="center" prop="tenantId" :show-overflow-tooltip="true" width="120"/> -->
          <el-table-column label="用户编号" align="center" prop="UserID" :show-overflow-tooltip="true"/>
          <el-table-column label="用户名称" align="center" prop="UserName" :show-overflow-tooltip="true" />
          <el-table-column label="手机号码" align="center" prop="UserPhone" :show-overflow-tooltip="true"/>
          <el-table-column label="证件类型" align="center" prop="IdType" :show-overflow-tooltip="true"/>
          <el-table-column label="证件号码" align="center" prop="UserCode" :show-overflow-tooltip="true"/>
          <el-table-column label="用户地址" align="center" prop="UserAddress" :show-overflow-tooltip="true"/>
          <el-table-column label="备注" align="center" prop="ReMark" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="用户状态" align="center" prop="UserMark" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.user_status" :value="scope.row.UserMark"/>
            </template>
          </el-table-column> -->
        </el-table>

        <pagination
          v-show="usertotal>0"
          :total="usertotal"
          :page.sync="userQueryParams.pageNum"
          :limit.sync="userQueryParams.pageSize"
          @pagination="getAllxbUser"
        />
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onOk">确 定</el-button>
        <el-button @click="onCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 换表 绑定表 -->
    <el-dialog :title="title" :visible.sync="openBindTerminal" width="calc(100w -200px)" append-to-body @close="onCancel">
      <!-- 搜索 -->
      <el-row>
        <el-form :model="terminalQueryParams" ref="queryTerminalForm" size="small" label-width="100px" :inline="true">
          <!-- <el-form-item label="归属水司" prop="tenantId">
            <el-input
              v-model="terminalQueryParams.tenantId"
              placeholder="请输入归属水司"
              clearable
              @keyup.enter.native="handleQueryTerminal"
              class="input_w"
            />
          </el-form-item> -->
          <el-form-item label="设备编号" prop="TerminalID">
            <el-input
              v-model="terminalQueryParams.TerminalID"
              placeholder="请输入设备编号"
              clearable
              @keyup.enter.native="handleQueryTerminal"
              class="input_w"
            />
          </el-form-item>
          <el-form-item label="通讯地址" prop="communicateAddress">
            <el-input
              v-model="terminalQueryParams.communicateAddress"
              placeholder="请输入通讯地址"
              clearable
              @keyup.enter.native="handleQueryTerminal"
              class="input_w"
            />
          </el-form-item>
          <!-- <el-form-item label="楼栋编号" prop="ldId">
            <el-input
              v-model="terminalQueryParams.ldId"
              placeholder="请输入楼栋编号"
              clearable
              @keyup.enter.native="handleQueryTerminal"
              class="input_w"
            />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="handleQueryTerminal" size="mini">查询</el-button>
            <el-button @click="resetTerminalQuery" size="mini">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!-- 表格 -->
      <el-row>
        <el-table v-loading="terminalloading" :data="terminalxbList" @row-click="singleTerminalElection" highlight-current-row style="height: calc(100vh - 416px);overflow: auto;">
          <!-- <el-table-column type="selection" width="55" align="center" fixed/> -->
          <el-table-column align="center" width="55" label="选择">
            <template slot-scope="scope">
              <el-radio v-model="templateTerminalSelection" :label="scope.row.ID" class="radio"><span v-html="'\u00a0'"></span></el-radio>
            </template>
          </el-table-column>
          <!-- <el-table-column label="自增主键" align="center" prop="ID" :show-overflow-tooltip="true"/> -->
          <!-- <el-table-column label="归属水司" align="center" prop="tenantId" width="120" :show-overflow-tooltip="true"/> -->
          <el-table-column label="设备编号" align="center" prop="TerminalID" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="门牌号" align="center" prop="roomName" :show-overflow-tooltip="true"/> -->
          <el-table-column label="厂家名称" align="center" prop="SupplierID" :show-overflow-tooltip="true" width='150'>
            <template slot-scope="scope">
              <dict-tag :options="dict.type.terminal_supplier" :value="scope.row.SupplierID"/>
            </template>
          </el-table-column>
          <el-table-column label="表型号" align="center" prop="TypeID" :show-overflow-tooltip="true" width='150'>
            <template slot-scope="scope">
              <dict-tag :options="dict.type.module_type" :value="scope.row.TypeID"/>
            </template>
          </el-table-column>
          <el-table-column label="表底数" align="center" prop="BaseReading" :show-overflow-tooltip="true"/>
          <el-table-column label="是否带阀控" align="center" prop="ValveControl" width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.yes_no" :value="scope.row.ValveControl"/>
            </template>
          </el-table-column>
          <el-table-column label="阀门地址" align="center" prop="ValveAddress" :show-overflow-tooltip="true"/>
          <el-table-column label="启用日期" align="center" prop="InstallDate" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.InstallDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="安装地址" align="center" prop="InstallAddress" :show-overflow-tooltip="true"/>
          <el-table-column label="通讯地址" align="center" prop="communicateAddress" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="换表标志" align="center" prop="ChangeMark" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.ValveControl === 0">否</el-tag>
              <el-tag v-if="scope.row.ValveControl === 1">是</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="新表地址" align="center" prop="terminalNew" :show-overflow-tooltip="true"/> -->
          <!-- <el-table-column label="删除标志" align="center" prop="DeleteMark" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.DeleteMark"/>
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="抄表周期" align="center" prop="MeterReaderCycle" :show-overflow-tooltip="true"/> -->
          <el-table-column label="抄表周期" align="center" prop="MeterReaderCycle" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.reader_cycle" :value="scope.row.MeterReaderCycle"/>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="terminaltotal>0"
          :total="terminaltotal"
          :page.sync="terminalQueryParams.pageNum"
          :limit.sync="terminalQueryParams.pageSize"
          @pagination="getAllterminalList"
        />
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onOk">确 定</el-button>
        <el-button @click="onCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoom, getRoom, delRoom, addRoom, updateRoom, bindterminal, binduser, replaceterminal, replaceuser, getAreald} from "@/api/record/room";
import { getAreasList } from '@/api/basedata/areas'
import { listUsersxb } from "@/api/record/usersxb"
import { listTerminalxb } from "@/api/record/terminalxb";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";

export default {
  name: "Room",
  dicts: ['belong_department', 'module_type', 'user_status','terminal_supplier', 'yes_no', 'reader_cycle'],
  components: { Treeselect },
  data() {
    return {
      templateUserSelection: '',
      templateTerminalSelection: '',
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basedata/room/importData"
      },
      // selectUserId: null,
      // selectTerminal: null,
      selectUserList:[],
      selectTerminalList:[],
      lglist: [],
      optionsObj: {},
      // 下拉框下的区域树
      // treeAreaCode: null,
      AreaName: null,
      selectOptions: {},
      flag: false,
      size:'small',
      collapseAble: false,
      fold: false,
      maxShow: '4',
      labelWidth: '100px',
      childrens: [],
      // 列信息
      columns: [
        // { key: 0, label: `平台表单主键`, visible: false },
        // { key: 1, label: `租户编号`, visible: true },
        { key: 0, label: `归属楼栋编号`, visible: true },
        { key: 1, label: `楼层`, visible: true },
        { key: 2, label: `门牌号`, visible: true },
        { key: 3, label: `建筑面积`, visible: true },
        { key: 4, label: `入住人数`, visible: true },
        { key: 5, label: `用户编号`, visible: true },
        { key: 6, label: `设备编号`, visible: true },
        { key: 7, label: `用户名称`, visible: true },
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 区域树选项
      areaOptions: [],
      areatreeOptions: [],
      // 区域名称
      keyWordName: undefined,
      // 树状态
      treeVisibale: true,
      // 遮罩层
      userloading: true,
      terminalloading: false,
      roomloading: false,
      treeloading: false,
      areatreeLoading: false,
      // 选中数组
      ids: [],
      roomids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      usertotal: 0,
      terminaltotal: 0,
      // 楼栋房间表格数据
      roomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openBindUser: false,
      openBindTerminal: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        ldName: null,
        ldLc: null,
        roomName: null,
        UserID: null,
        TerminalID: null,
        TerminalType: null,
        treeAreaCode: null,
        treeLdId: null,
      },
      usersList: [],
      terminalxbList: [],

      // 查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 20,
        tenantId: null,
        UserName: null,
        DeleteMark: null,
        UserMark: 1,
        UserID: null,
      },
      terminalQueryParams: {
        pageNum: 1,
        pageSize: 20,
        // tenantId: null,
        TerminalID: null,
        ldId: null,
        isBound: false,
        communicateAddress: null,
        TerminalMark: 1,
      },
      // 表单参数
      form: {},
      // 过户记录表单参数
      // transferrecordform: {
      //   tenantId: null,
      //   oldUserid: null,
      //   newUserid: null,
      //   ghTime: null
      // },
      // replaceRecordForm: {
      //   ID: null,
      //   tenantId: null,
      //   TerminalType: null,
      //   oldTerminalid: null,
      //   newTerminalid: null,
      //   ChangeTime: null,
      //   OldSettlementReading: null,
      //   newBasereading: null,
      //   Operator: null,
      //   ReMark: null
      // },
      // 表单校验
      rules: {
        // treeAreaCode: [
        //   { required: true, message: "区域不能为空", trigger: "change" }
        // ],
        roomName: [
          { required: true, message: "门牌号不能为空", trigger: "blur" }
        ],
        areaCode: [
          { required: true, message: "区域不能为空", trigger: "change" }
        ],
        ldId: [
          { required: true, message: "归属楼栋不能为空", trigger: "blur" }
        ],
        tenantId: [
          { required: true, message: "归属水司不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getAreaTree();
    // this.getAllxbUser()
    // this.getAllterminalList()
  },
  mounted() {
    this.getAreaTreeList()
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  watch: {
    // 根据名称筛选区域树
    keyWordName(val) {
      this.$refs.tree.filter(val);
    },
    AreaName(val){
      this.$refs.areatree.filter(val)
    },
    'form.areaCode': 'currDeptChange'
  },
  methods: {
    singleUserElection(row) {
      this.templateUserSelection = row.ID
      this.selectUserList = this.usersList.filter((item) => item.ID === row.ID)
    },
    singleTerminalElection(row){
      this.templateTerminalSelection = row.ID
      this.selectTerminalList = this.terminalxbList.filter((item) => item.ID === row.ID)
    },
    selectable(selection, row){
      const selectArr = this.$refs.userTable.selection;
      const state = selectArr.some((item) => item.id = row.id )
      return (selectArr.length < 1 || state)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "户表档案导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
      //去掉children=null的属性
    normalizer(node){
      if(node.children==null||node.children=='null'){
        delete node.children;
      }
    },
    currDeptChange(val) {
      if (val) {
      	getAreald(val).then(response => {
        this.lglist = response.data
        this.optionsObj = {}
        this.lglist.map(item=>{
          this.optionsObj[item.ldId] = {...item}
        })
      })
      }
    },
    handleldselect(e){
      this.form.tenantId = this.optionsObj[e].tenantId
    },
    // 筛选节点
    filterTreeNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 单击下拉框中的数据
    handleSelectTree(data){
      this.selectOptions = data
      this.form.treeAreaCode = data.id
      this.form.areaCode = data.id

    },
    // /** 查询区域下拉树结构 */
    getAreaTreeList() {
      this.areatreeLoading = true
      let list_ = JSON.parse(localStorage.getItem('list'))
      list_.forEach((item) => {
        let obj = {
          id: item.areaCode,
          label: item.areaName,
          tenantId: item.tenant_id,
          children: item.children && item.children.length > 0 ? this.copyTreeList(item.children) : item.children
        }
        this.areatreeOptions.push(obj)
      })
      this.areatreeLoading = false
    },
    copyTreeList(list) {
      list.forEach((item) => {
        item.id = item.areaCode;
        item.label = item.areaName;
        item.children = item.children;
        item.tenantId = item.tenant_id
        if (item.children && item.children.length) {
          this.copyTreeList(item.children);
        }
      });
      return list;
    },
    // 初始化表格 解决表格固定操作列的问题
    init(){
      // 调用接口获取到数据后
      let _self = this
      this.$nextTick(() => {
        window.setTimeout(() => {
          _self.$refs.roomtable.doLayout()
        }, 100)
      })
    },
    // 获取所有用户信息
    getAllxbUser(){
      this.userloading = true
      listUsersxb(this.userQueryParams).then(response => {
        this.usersList = response.rows;
        this.usertotal = response.total;
        this.userloading = false;
      })
    },
    // 获取所有户表信息
    getAllterminalList(){
      this.terminalloading = true;
      listTerminalxb(this.terminalQueryParams).then(response => {
        this.terminalxbList = response.rows;
        this.terminaltotal = response.total;
        this.terminalloading = false;
      });
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      // this.resetQueryParams();
      // this.resetQuery()
      if( data.treeType === 1){
        this.queryParams.treeAreaCode = data.areaCode;
        this.getList()
      }else if(data.treeType === 2){
        this.queryParams.treeLdId = data.ldId
        this.getList()
      }
    },
     /** 查询区域下拉树结构 */
    getAreaTree() {
      this.treeloading = true
      let list_ = JSON.parse(localStorage.getItem('list'))
      list_.forEach((item) => {
        // let childrens = item.children.concat(item.louDongs)
        if(item.children === null){
          item.children = []
        }
        if(item.louDongs !=null && item.louDongs !=[]){
          item.children = item.children.concat(item.louDongs)
        }
        let childrens = item.children
        let obj = {
          id: item.treeType === 1?  item.areaCode : item.id,
          label: item.treeType === 1? item.areaName : item.ldName,
          children: item.children && item.children.length > 0 ? this.copyTree(childrens) : item.children
        }
        this.areaOptions.push(obj)
        this.treeloading = false
      })
    },
    copyTree(list) {
      list.forEach((item) => {
        let flag1 = false
        let childrens = []

        if((null != item.children  && item.children.length > 0)||(null != item.louDongs  && item.louDongs.length > 0)){
          flag1 = true
          if(item && item.children && item.louDongs){
            childrens = item.children.concat(item.louDongs)
          }else if(item && item.children && item.louDongs == null){
            childrens = item.children
          }else if(item && item.louDongs && item.children == null ){
            childrens = item.louDongs
          }
        }else{
          flag1 = false
        }
        item.id = item.treeType === 1?  item.areaCode : item.id;
        item.label = item.treeType === 1? item.areaName : item.ldName;
        item.children = childrens;
        if (flag1) {
          this.copyTree(item.children);
        }
      });
      return list;
    },
    // 改变tree的显示与隐藏
    changeTreeShow(){
      this.treeVisibale =!this.treeVisibale
    },
    /** 查询楼栋房间列表 */
    getList() {
      this.init()
      this.roomloading = true;
      listRoom(this.queryParams).then(response => {
        this.roomList = response.rows;
        this.total = response.total;
        this.roomloading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    onCancel(){
      if(this.title==='绑定用户' || this.title==='房间过户'){
        this.openBindUser = false
        this.selectUserList = []
      }else if(this.title==='绑表' || this.title==='换表'){
        this.openBindTerminal = false
        this.selectTerminalList = []
      }
    },
    // 表单重置
    reset() {
      this.form = {
        ID: null,
        tenantId: null,
        ldId: null,
        ldLc: null,
        roomName: null,
        BuiltUpArea: null,
        UserNumber: null,
        UserID: null,
        TerminalID: null,
        TerminalType: null,
        oldTerminalId: null,
        newTerminalId: null,
        oldUserId: null,
        newUserId: null,
        treeAreaCode: null,
        areaCode: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
     /** 用户搜索按钮操作 */
     handleQueryUser() {
      this.userQueryParams.pageNum = 1;
      this.getAllxbUser();
    },
    // 表搜索按钮
    handleQueryTerminal() {
      this.terminalQueryParams.pageNum = 1;
      this.getAllterminalList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.tree.setCurrentKey(null);
      this.queryParams.treeLdId = null,
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetTerminalQuery(){
      this.templateTerminalSelection = ''
      this.resetForm('queryTerminalForm')
      this.handleQueryTerminal()
    },
    resetUserQuery(){
      this.templateUserSelection = ''
      this.resetForm('queryUserForm')
      this.handleQueryUser()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.roomids = selection.map(item => item.roomName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加房间";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ID = row.id || this.ids
      this.form.treeAreaCode = null
      getRoom(ID).then(response => {
        this.form = response.data;
        this.form.areaCode = row.areaCode
        // this.selectOptions.id = row.areaCode
        // this.selectOptions.label = "测试楼栋"
        this.open = true;
        this.title = "修改房间";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title === "修改房间") {
            updateRoom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else if(this.title === "添加房间"){
            addRoom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      debugger
      const IDs = row.id || this.ids;
      const roomIds = row.roomName || this.roomids
      this.$modal.confirm('是否确认删除门牌号为"' + roomIds + '"的数据项？').then(function() {
        return delRoom(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basedata/room/export', {
        ...this.queryParams
      }, `room_${new Date().getTime()}.xlsx`)
    },
    // 绑定用户弹窗
    handleBindUser(row) {
      this.templateUserSelection =''
      this.resetUserQuery()
      this.getAllxbUser()
      this.form = row
      this.openBindUser = true
      this.title = '绑定用户'
    },
    // 房间过户弹窗
    handleTransferUser(row) {
      this.templateUserSelection =''
      this.resetUserQuery()
      this.form = row
      this.form.oldUserId = row.UserID
      this.getAllxbUser()
      this.$modal.confirm('是否确认重新绑定用户？').then(() => {
        this.title = '房间过户'
        this.openBindUser = true
      }).catch(() => {});
    },
    // 绑表弹窗
    handleBindTerminal(row) {
      this.templateTerminalSelection = ''
      this.resetTerminalQuery()
      this.form = row
      this.getAllterminalList()
      this.openBindTerminal = true
      this.title = '绑表'
    },
    // 换表弹窗
    handleTransferTerminal(row) {
      this.templateTerminalSelection = ''
      this.resetTerminalQuery()
      this.form = row
      this.form.oldTerminalId = row.TerminalID
      this.getAllterminalList()
      this.$modal.confirm('是否确认重新绑定表？').then(() => {
        this.title = '换表'
        this.openBindTerminal = true
      }).catch(() => {});
    },
    // 确定按钮
    onOk(){
      if((this.selectUserList.length == 0 && this.title === '绑定用户') || (this.selectUserList.length == 0 && this.title === '房间过户')){
        this.$modal.msgWarning('最少选择一个用户')
        return
      }
      if((this.selectTerminalList.length == 0 && this.title === '绑表') || (this.selectTerminalList.length == 0 && this.title === '换表')){
        this.$modal.msgWarning('最少选择一个表')
        return
      }
      if(this.title === '绑定用户'){
        this.form.UserID = this.selectUserList[0].UserID
        binduser(this.form).then(response => {
          if(response.code === 200){
            this.$modal.msgSuccess("绑定用户成功");
            this.openBindUser = false;
            this.getList();
          }else{
            this.$modal.msgError("绑定用户失败");
          }
        });
      }else if(this.title === '房间过户'){
        this.form.newUserId = this.selectUserList[0].UserID

        replaceuser(this.form).then(response => {
          if(response.code === 200){
            this.$modal.msgSuccess("过户成功");
            this.getList();
            // this.transferrecordform.ghTime = new Date()
            this.openBindUser = false;
          }
        })
      }else if(this.title === '绑表'){
        this.form.TerminalID = this.selectTerminalList[0].TerminalID
        bindterminal(this.form).then(response => {
          if(response.code === 200){
            this.$modal.msgSuccess("绑表成功");
            this.openBindTerminal = false;
            this.getList();
          }
        })
      }else if(this.title === '换表'){
        this.form.newTerminalId = this.selectTerminalList[0].TerminalID
        replaceterminal(this.form).then(response => {
          if(response.code === 200){
              this.$modal.msgSuccess("换表成功");
              this.getList()
              this.openBindTerminal = false;
            }
        })
      }
    },
  }
};
</script>
<style lang="scss" scoped>

::v-deep.el-tree-node__content {
    height: 38px;
}
// 设置下拉图标位置
::v-deep.el-tree-node__expand-icon {
    position: absolute;
    right: 1%;
}
// 不使用slot自定义列表时label样式控制
::v-deep.el-tree-node__label {
    padding-left: 15px;
}
.form_col{
  width: 80%;
  ::v-deep .el-form {
    width: 100%;
  }
  ::v-deep .el-form-item {
    width: 25%;
  }
}
.form_query{
  width: 20%;
  text-align: right;
}
.option {
    height: auto;
    line-height: 1;
    padding: 0;
    background-color: #fff;
}
.tree {
    padding: 4px 20px;
    font-weight: 400;
}
.radio{
  white-space: pre-line;
}
</style>
